package com.doit.mr.day03;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @DATE 2021/12/8/17:22
 * @Author MDK
 * @Version 2021.2.2
 **/
public class Line {
    //Mapper
    static class LineMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                String line = value.toString();
                String[] split = line.split(",");

                //截取点
                int x1 = Integer.parseInt(split[0]);
                int x2 = Integer.parseInt(split[1]);
                //生成线段经过的点
                for (int i = x1; i < x2; i++) {
                    IntWritable k = new IntWritable(i);
                    IntWritable v = new IntWritable(1);
                    context.write(k,v);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //Reducer
    static class LineReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable>{
        @Override
        protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int cnt = 0;
            for (IntWritable value : values) {
                cnt++;
            }
            context.write(key,new IntWritable(cnt));
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "wordCount");
        job.setMapperClass(LineMapper.class);
        job.setReducerClass(LineReducer.class);

        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job,new Path("D:\\mrdata\\line\\input"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\mrdata\\line\\output"));
        job.waitForCompletion(true);
    }
}
